import { addApplyRecordUsingPost } from '@/services/backend/applyRecordController';
import {
  listPeripheralInfoTypeUsingGet,
  listPeripheralInfoVoByPageUsingPost,
} from '@/services/backend/peripheralInfoController';
import { useModel } from '@umijs/max';
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Pagination,
  Row,
  Skeleton,
  Space,
  Tabs,
  Typography,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { initialButtonNames } from '@/constants';

const Home: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<API.PeripheralInfoVO[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [curTab, setCurTab] = useState(0);
  const [open, setOpen] = useState(false);
  const [tmpStock, setTmpStock] = useState(0);
  const [selectedId, setSelectedId] = useState(0);

  const { initialState } = useModel('@@initialState');
  const [form] = Form.useForm();

  const [buttonNames, setButtonNames] = useState(initialButtonNames);

  const handleApplyClick = (id: any, stock: any) => {
    setTmpStock(stock);
    setSelectedId(id);
    setOpen(true);
  };

  function changeTab(index: number) {
    setCurTab(index);
  }

  const handleApply = async (content: any, applyNums: any) => {
    const hide = message.loading('正在申请');
    try {
      await addApplyRecordUsingPost({
        peripheralId: selectedId,
        content,
        applyNums,
      });
      hide();
      message.success('申请成功');
      loadData();
      setOpen(false);
      form.resetFields();
    } catch (error: any) {
      hide();
      message.error('申请失败，' + error.message);
    }
  };

  const loadData = async (current = 1, pageSize = 12) => {
    setLoading(true);
    try {
      const buttonNamesResponse = await listPeripheralInfoTypeUsingGet();
      const fetchedButtonNames = buttonNamesResponse?.data || [];
      setButtonNames(initialButtonNames.concat(fetchedButtonNames));

      const res = await listPeripheralInfoVoByPageUsingPost({
        current,
        pageSize,
        type: curTab === 0 ? [] : [buttonNames[curTab]],
        status: 1
      });
      setList(res?.data?.records ?? []);
      setTotal(res?.data?.total ?? 0);
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
    setLoading(false);
  };

  function confirm() {
    const content = form.getFieldValue('content');
    const applyNums = form.getFieldValue('applyNums') || 1;
    if (!content) {
      message.error('请输入审批意见');
      return;
    }
    handleApply(content, applyNums);
  }

  function jumpExternalLink(link: string) {
    window.open(link);
  }

  useEffect(() => {
    loadData();
  }, [curTab]);

  return (
    <div style={{ padding: 24, background: '#f5f5f5' }}>
      <Tabs
        activeKey={curTab.toString()}
        onChange={(key) => changeTab(Number(key))}
        type="card"
        items={buttonNames.map((name, index) => ({
          key: index.toString(),
          label: name,
        }))}
      />

      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {loading
          ? new Array(8).fill(1).map((_, index) => (
            <Col span={6} key={index}>
              <Card>
                <Skeleton active />
              </Card>
            </Col>
          ))
          : list.map((item) => (
            <Col span={6} key={item.id}>
              <Card
                hoverable
                cover={
                  <img
                    alt={item.name}
                    src={item.cover}
                    style={{ height: 240, objectFit: 'cover' }}
                    onClick={() => jumpExternalLink(item.purchaseLink || 'https://code-nav.cn')}
                  />
                }
              >
                <Space direction="vertical" size="small" style={{ width: '100%' }}>
                  <Typography.Text strong ellipsis>
                    {item.name}
                  </Typography.Text>
                  {/*<Typography.Text type="danger">*/}
                  {/*  ¥{(item.price || 0) / 100}*/}
                  {/*</Typography.Text>*/}
                  {/*<Typography.Text type="secondary">*/}
                  {/*  {(item.stock || 0) > 0*/}
                  {/*    ? `剩余库存：${item.stock} 件`*/}
                  {/*    : '库存不足'}*/}
                  {/*</Typography.Text>*/}
                  {/*{initialState?.currentUser &&*/}
                  {/*  ['internal', 'admin'].includes(initialState.currentUser.userRole || '') && (*/}
                  {/*    <Button*/}
                  {/*      type="primary"*/}
                  {/*      block*/}
                  {/*      disabled={(item.stock || 0) <= 0}*/}
                  {/*      onClick={() => handleApplyClick(item.id, item.stock)}*/}
                  {/*    >*/}
                  {/*      {(item.stock || 0) <= 0 ? '库存为空' : '申请周边'}*/}
                  {/*    </Button>*/}
                  {/*  )}*/}
                </Space>
              </Card>
            </Col>
          ))}
      </Row>

      <div style={{ marginTop: 24, textAlign: 'right' }}>
        <Pagination
          total={total}
          pageSize={12}
          onChange={(page, pageSize) => loadData(page, pageSize)}
        />
      </div>

      <Modal
        title="周边申请"
        open={open}
        onOk={confirm}
        onCancel={() => {
          setOpen(false);
          form.resetFields();
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="申请理由"
            name="content"
            rules={[{ required: true, message: '请填写申请内容' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            label="申请数量"
            name="applyNums"
            rules={[{ required: true, message: '请填写申请数量' }]}
          >
            <InputNumber min={1} max={tmpStock} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Home;
